/**
 * @program: clms-second
 * @description: 全局过滤器
 * @author: mitu_echo
 * @create: 2021-07-22 18:44
 **/

package com.second.appgateway.config;

import com.alibaba.fastjson.JSON;
import com.second.common.pojo.R;
import com.second.common.util.JwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

//@Component
public class Filter implements GlobalFilter, Ordered {

    @Autowired
    private RsaKeyProperties properties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /**
         * 要求访问所有的微服务时，都应该已经登录，否则则不允许进行访问
         * 将用户登录的信息存入 token 中，从 token 中读取数据，
         * 如果没有 token 表示还没有登录
         */
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        DataBuffer buffer = null;
        // 获取 token
        String token = request.getHeaders().getFirst("Token");
        // 获取请求路径
        String path = request.getPath().toString();

        // 判断请求路径中是否包含了 singInByup
        if (path.contains("/signInByup") || path.contains("/sendSms") || path.contains("/registerClient") || path.contains("/updatePwd")) {
            return chain.filter(exchange);
        } else {
            // 如果请求路径中没有 login ，表示直接请求其他微服务， 判断否是已经登录，是否有token
            // StringUtils.isNotEmpty()判断括号内的参数是否是空，不是空返回true，是空返回false
            // StringUtils.isEmpty()判断括号内的参数是否是空，是空返回true，不是空返回false
            if (StringUtils.isNotEmpty(token)) {
                if (JwtUtil.getInfoFromToken(token,properties.getPublicKey()) != null) {
                    return chain.filter(exchange);
                } else {
                    try {
                        R r = R.error();
                        r.setMessage("token不合法");
                        byte[] bytes = JSON.toJSONString(r).getBytes("utf-8");
                        buffer = response.bufferFactory().wrap(bytes);
                        response.setStatusCode(HttpStatus.UNAUTHORIZED);
                        response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return response.writeWith(Mono.just(buffer));
                }
            } else {
                try {
                    R r = R.error();
                    r.setMessage("请先进行登录");
                    byte[] bytes = JSON.toJSONString(r).getBytes("utf-8");
                    buffer = response.bufferFactory().wrap(bytes);
                    response.setStatusCode(HttpStatus.UNAUTHORIZED);
                    response.getHeaders().add("Content-Type","application/json;charset=UTF-8");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return response.writeWith(Mono.just(buffer));
            }
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
